﻿/// <reference path="functions.js" />
/// <reference path="../../Scripts/knockout.mapping-latest.debug.js" />
/// <reference path="jquery.elastislide.js" />

$(function ()
    {
    var my = {};

    textControl = function () {
        var id = ko.observable(0),
        itemID = ko.observable(0),
        align = ko.observable(2),
        isBold = ko.observable(false),
        isSelected = ko.observable(true),
        isItalic = ko.observable(false),
        fontFamily = ko.observable('VNI-Times'),
        fontSize = ko.observable(39),
        foreground = ko.observable('000000'),
        text = ko.observable('Add text here'),
        width = ko.observable('300'),
        height = ko.observable('100'),
        C_left = ko.observable('0'),
        C_top = ko.observable('0'),
        type = ko.observable('0'),
        unicodeText = ko.observable('Add text here'),
        getBoldStyle = ko.computed(function () {
            return isBold() ? 'bold' : 'normal';
        }),
        getAlignStyle = ko.computed(function () {
            switch (align()) {
                case 1:
                    return 'justify';
                    break;
                case 3:
                    return 'right';
                    break;
                case 0:
                    return 'center';
                    break;
                case 2:
                default:
                    return 'left';
            }
        }),

        getItalicStyle = ko.computed(function () {
            return isItalic() ? 'italic' : 'normal';
        });
        return {
            id : id,
            itemID: itemID,
            align: align,
            isBold: isBold,
            isSelected: isSelected,
            isItalic: isItalic,
            fontFamily: fontFamily,
            fontSize: fontSize,
            foreground: foreground,
            text: text,
            width: width,
            height: height,
            C_left: C_left,
            C_top: C_top,
            type: type,
            unicodeText: unicodeText,
            getBoldStyle: getBoldStyle,
            getAlignStyle: getAlignStyle,
            getItalicStyle: getItalicStyle
        }
    };

    my.vm = function () {
        var self = this,
            maxWidth = 480,
            maxHeight = 800,
            ratio = 1,
            projectName = ko.observable(""),
            previewLink = ko.observable(""),
            CommonGalleries = ko.observableArray([]),
            Item,
            itemControls = ko.observableArray(),
            Items = ko.observableArray([]),
            Templates = ko.observableArray([]),
            Galleries = ko.observableArray([]),
            backgroundSelectedIndex = ko.observable(),
            backgroundSelectedType = ko.observable(),
            backgroundDownloadUrl = ko.observable(""),
            backgroundDownloadMessage = ko.observable(""),

            backgroundSrc = ko.observable(),
            font = ko.observable('VNI-thufap2'),
            gIsBold = ko.observable(false),
            gIsItalic = ko.observable(false),
            foreground = ko.observable('000000'),
            gAlign = ko.observable(2),
            textControlSelected = ko.observable(-1),
            fontSize = ko.observable(39),
            left = ko.observable(0),
            top = ko.observable(0),
            width = ko.observable('200'),
            height = ko.observable('50'),
            templateName = ko.observable(""),
            templateDescription = ko.observable(""),
            templateID = ko.observable(0),
            colorControlInit = function (idSelector) {
                $(idSelector).jPicker(
                    {
                        window: // used to define the position of the popup window only useful in binded mode
                      {
                          title: null, // any title for the jPicker window itself - displays "Drag Markers To Pick A Color" if left null
                          effects:
                          {
                              type: 'slide', // effect used to show/hide an expandable picker. Acceptable values "slide", "show", "fade"
                              speed:
                              {
                                  show: 'slow', // duration of "show" effect. Acceptable values are "fast", "slow", or time in ms
                                  hide: 'fast' // duration of "hide" effect. Acceptable value are "fast", "slow", or time in ms
                              }
                          },
                          position:
                          {
                              x: 'screenCenter', // acceptable values "left", "center", "right", "screenCenter", or relative px value
                              y: '0px', // acceptable values "top", "bottom", "center", or relative px value
                          },
                          expandable: false, // default to large static picker - set to true to make an expandable picker (small icon with popup) - set
                          // automatically when binded to input element
                          liveUpdate: true, // set false if you want the user to click "OK" before the binded input box updates values (always "true"
                          // for expandable picker)
                          alphaSupport: false, // set to true to enable alpha picking
                          alphaPrecision: 0, // set decimal precision for alpha percentage display - hex codes do not map directly to percentage
                          // integers - range 0-2
                          updateInputColor: true // set to false to prevent binded input colors from changing
                      },
                        images:
                      {
                          clientPath: '/Content/themes/images/', // Path to image files
                      }
                    },
                    function (color, context) {
                        if (idSelector == '#colorValue') {
                            var hex = color.val('hex');
                            foreground(hex);
                            if (textControlSelected() > -1) itemControls()[textControlSelected()].foreground(hex);

                        }
                    }
                    );
            },
            uploadBackground = function () {
                var url = '/editor/UploadImageFromComputer';
                var formData = new FormData($('#uploadFromComputerForm')[0]);

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    async: false,
                    success: function (response) {
                        switch (response.Status) {
                            case 1:
                                var temp = ko.mapping.fromJS(response.Gallery);
                                Galleries.push(temp);
                                break;
                            case 0:
                                break;
                        }
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
            },
            downloadBackground = function (data, event) {
                var extension = backgroundDownloadUrl().split('.');
                var length = extension.length;
                extension = extension[length - 1];
                if (extension == 'jpg' || extension == 'png'
                    || extension == 'jpeg') {
                    var data = {
                        url: backgroundDownloadUrl()
                    };
                   
                    $.ajax({
                        url: '/editor/UploadImage',
                        type: 'post',
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        data: ko.mapping.toJSON(data),
                        cache: false,
                        async: false,
                        dataType: 'json',
                        success: function (response) {
                            switch (response.Status) {
                                case 1:
                                    var temp = ko.mapping.fromJS(response.Gallery);
                                    Galleries.push(temp);
                                    backgroundDownloadMessage("");
                                    break;
                                case 0:
                                    backgroundDownloadMessage("File not found!");
                                    break;
                            }
                        }
                    });
                }
                else {
                    backgroundDownloadMessage("File extension " + extension + " is not in Image type (PNG/JPG/JPEG)");
                }
            },
            backgroundControlReset = function () {
                $('.bg-gallery').hide();
                $('.bg-url').hide();
                $('.bg-upload').hide();

                $('.bg-header > ul').children('li').removeClass('selected');
            },
            backgroundControlTabChanged = function (data, event) {
                backgroundControlReset();
                var selectorID = event.target.id;
                $('#' + selectorID).addClass('selected');
                $('.' + selectorID).show(1000);

            },
            backgroundSelect = function (data, event) {
                var selectedID = event.currentTarget.id;
                var selectedArr = selectedID.split('-');
                backgroundSelectedIndex = selectedArr[1];
                backgroundSelectedType = selectedArr[0];
                backgroundReset();
                $('#' + selectedID).addClass('selected');

                backgroundSrc(data.url());
                //$('.editor-bg').attr('src', Item.background());
            },
            backgroundReset = function () {
                $('#galleries').children('li').children('a').removeClass('selected');
                $('#common-galleries').children('li').children('a').removeClass('selected');
            },
            backgroundControlInit = function () {
                backgroundControlReset();
                $('#bg-gallery').addClass('selected');
                $('.bg-gallery').show(1000);
                $('.bg-select').hide(500);
            },
            backgroundCancel = function () {
                $('.bg-select').hide(500);
            },
            backgroundShow = function () {
                $('.bg-select').show(500);
            },
            backgroundOK = function () {
                Item.background(backgroundSrc());
                $('.editor-bg').attr('src', Item.background());
                $('#ed-scr').css('background-image', 'url(' + backgroundSrc() + ')');
                backgroundCancel();
            },
            setAlign = function (value) {
                gAlign(value);
                if (textControlSelected() > -1) itemControls()[textControlSelected()].align(value);
                $('#align-controls').children('button').removeClass('selected');
                switch (value) {
                    case 1:
                        $('.justify-icon').addClass('selected');
                        break;
                    case 3:
                        $('.right-icon').addClass('selected');
                        break;
                    case 0:
                        $('.center-icon').addClass('selected');
                        break;
                    case 2:
                    default:
                        $('.left-icon').addClass('selected');
                }

            },
            setBold = function (data, event) {
                gIsBold(!gIsBold());
                if (textControlSelected() > -1) itemControls()[textControlSelected()].isBold(gIsBold());
                var id = event.target.id;

                gIsBold() ? $('#' + id).addClass('selected') : $('#' + id).removeClass('selected');
            },
            
            setItalic = function (data, event) {
                gIsItalic(!gIsItalic());
                if (textControlSelected() > -1) itemControls()[textControlSelected()].isItalic(gIsItalic());
                var id = event.target.id;

                gIsItalic() ? $('#' + id).addClass('selected') : $('#' + id).removeClass('selected');
            },
            changeFont = function () {
                if (textControlSelected() > -1) {
                    itemControls()[textControlSelected()].fontFamily(font()[0]);
                   }
            },
            uiInit = function () {
                
                colorControlInit('#colorValue');
                backgroundControlInit();
                fontSizeInput();
                updateFontSize();
                $('#common-galleries').elastislide();

                textControlDone();
                initDragAndResize();

                //export a event
                $('#aPreview').click(function () {
                    //openNewWindow(previewLink());
                    window.open(previewLink(), "newwin");
                });
            },

                initData = function () {
                    var data = {
                        id: $.QueryString['id'] == null ? 0 : $.QueryString['id'],
                        type: $.QueryString['type'] == null ? 'project' : $.QueryString['type']
                    }

                    $.ajax({
                        url: "/editor/InitializeJSON",
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        async: false,
                        data: JSON.stringify(data),
                        type: "post",
                        success: function (response) {
                            ko.mapping.fromJS(response.CommonGalleries, {}, CommonGalleries);
                            Item = ko.mapping.fromJS(response.Item);
                            ko.mapping.fromJS(response.Items, {}, Items);
                            ko.mapping.fromJS(response.Templates, {}, Templates);
                            ko.mapping.fromJS(response.Galleries, {}, Galleries);

                            response.Item.itemControls.forEach(function (entry) {
                                var obj = new textControl;

                                ko.mapping.fromJS(entry, {}, obj);

                                obj.C_left(obj.C_left() * ratio);
                                obj.C_top(obj.C_top() * ratio);
                                obj.width(obj.width() * ratio);
                                obj.height(obj.height() * ratio);

                                itemControls.push(obj);
                            });

                            if (itemControls.length > 0)
                                textControlSelected(0);
                            //init background
                            backgroundSrc(Item.background());
                            $('#ed-scr').css('background-image', 'url(' + backgroundSrc() + ')');

                            //init global data
                            if (Item.id() > 0)
                            {
                                projectName(Item.name());
                                if (projectName() == null)
                                    projectName('');
                            }
                            templateID(response.TemplateID);
                        }
                    });
                },
            newTextControl = function () {
                var obj = new textControl().fontSize(fontSize()).
                                            foreground(foreground())
                                            .fontFamily(font())
                                            .align(gAlign())
                                            .isBold(gIsBold())
                                            .isItalic(gIsItalic())
                                            .isSelected(true);

                itemControls.push(obj);
                textControlSelected(itemControls.indexOf(obj));

                initDragAndResize();
                textControlDone();
            },
            initDragAndResize = function () {
                $('.editor-screen').children('li').resizable({
                    resize: function (event, ui) {
                            var id = event.target.id;
                            var index = id.split('-')[1];
                            textControlSelected(index);
                            itemControls()[textControlSelected()].width(ui.size.width);
                            itemControls()[textControlSelected()].height(ui.size.height);
                        
                    }
                });
                $('.editor-screen').children('li').draggable({
                    stop: function (event, ui) {
                            var id = event.target.id;
                            var index = id.split('-')[1];
                            textControlSelected(index);

                            var selector = $('#' + id);
                            var maxX = maxWidth - selector[0].clientWidth;
                            var maxY = maxHeight - selector[0].clientHeight;

                            var posx = ui.position.left < 0 ? 0 :
                                ui.position.left > maxX ? maxX : ui.position.left;
                            var posy = ui.position.top < 0 ? 0 : ui.position.top > maxY ? maxY : ui.position.top;

                            itemControls()[textControlSelected()].C_left(posx);
                            itemControls()[textControlSelected()].C_top(posy);

                            if (ui.position.left < 0 || ui.position.left > maxX
                                || ui.position.top < 0 || ui.position.top > maxY) {

                                selector.css("left", posx + 'px')
                                selector.css("top", posy + 'px');
                            }

                    }
                });
            },
            fontSizeInput = function () {
                $('#fontSizetb').keydown(function (event) {
                    // Allow: backspace, delete, tab, escape, and enter
                    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
                        // Allow: Ctrl+A
                        (event.keyCode == 65 && event.ctrlKey === true) ||
                        // Allow: home, end, left, right
                        (event.keyCode >= 35 && event.keyCode <= 39)) {
                        // let it happen, don't do anything
                        return;
                    }
                    else {
                        // Ensure that it is a number and stop the keypress
                        if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                            event.preventDefault();
                        }
                    }
                });
            },
            updateFontSize = function () {
                $('#fontSizetb').blur(function () {
                    if (textControlSelected() > -1) itemControls()[textControlSelected()].fontSize(fontSize());
                });
            },
            textControlEdit = function (data, event) {
                var id = event.target.id;
                var parent = $('#' + id).parent('li');
                var index = id.split('-')[1];
                parent.children('textarea').show().focus();
                parent.children('span').hide();
                parent.children('button').hide();

                if (textControlSelected() != index) {
                    textControlSelected(index);
                    ChangeTextControlInterface();
                }
            },
            textControlDelete = function (data, event) {
                itemControls.remove(data);
            },
            textControlDone = function () {
                $('.editor-screen > li > textarea').blur(function (event) {
                    var id = event.target.id;
                    var parent = $('#' + id).parent('li');
                    parent.children('textarea').hide();
                    parent.children('span').show();
                    parent.children('button').show();
                });
            },
            ChangeTextControlInterface = function () {
                var selected = itemControls()[textControlSelected()];
                fontSize(selected.fontSize());
                foreground(selected.foreground());
                font(selected.fontFamily());
                gAlign(selected.align());
                gIsBold(selected.isBold());
                gIsItalic(selected.isItalic());

                $('#align-controls').children('button').removeClass('selected');
                switch (gAlign()) {
                    case 1:
                        $('.justify-icon').addClass('selected');
                        break;
                    case 3:
                        $('.right-icon').addClass('selected');
                        break;
                    case 0:
                        $('.center-icon').addClass('selected');
                        break;
                    case 2:
                    default:
                        $('.left-icon').addClass('selected');
                };

                gIsBold() ? $('#bold-control').addClass('selected') : $('#bold-control').removeClass('selected');
                gIsItalic() ? $('#italic-control').addClass('selected') : $('#italic-control').removeClass('selected');
                $.jPicker.List[0].color.active.val('ahex', foreground());
            },
            saveItem = function () {
                if (projectName().length > 0)
                {
                    Item.itemControls = itemControls;
                    Item.name(projectName());
                    var data = {
                        Ratio: ratio,
                        Item: Item
                    };
                    var json = ko.mapping.toJSON(data);
                    $.ajax({
                        type: "POST",
                        url: '/Editor/SaveItem',
                        cache: false,
                        contentType: 'application/json; charset=utf-8',
                        data: json
                    }).done(function (id) {
                        if (id > 0) {
                            Item.id(id);
                            alert("Saved successfully!");
                            $('.prj-save-div').hide(500);
                        }
                    });
                }
                
            },
            cancelTemplate = function () {
                $('.tpl-save-div').hide(500);
            },
            openTemplateBox = function () {
                $('.tpl-save-div').show(500);
                $('#tbTemplateName').focus();
            },
            saveTemplate = function () {
                if (templateName().length == 0) {
                    $('#tbTemplateName').focus();
                }
                else if (templateDescription().length == 0) 
                {
                    $('#tbTemplateDescription').focus();
                }
                else{
                    Item.itemControls = itemControls;

                    var data = {
                        Ratio: ratio,
                        Item: Item,
                        id: templateID,
                        name: templateName,
                        description: templateDescription
                    };
                    var json = ko.mapping.toJSON(data);
                    $.ajax({
                        type: "POST",
                        url: '/Editor/SaveTemplate',
                        cache: false,
                        contentType: 'application/json; charset=utf-8',
                        data: json
                    }).done(function (id) {
                        if (id > 0) {
                            templateID(id);
                            alert("Saved successfully!");
                            cancelTemplate();
                        }
                    });
                }
            },
            exportImage = function () {
                Item.itemControls = itemControls;

                var data = {
                    Ratio: ratio,
                    Item: Item
                };
                var json = ko.mapping.toJSON(data);
                $.ajax({
                    type: "POST",
                    url: '/editor/ExportImg',
                    cache: false,
                    contentType: 'application/json; charset=utf-8',
                    data: json,
                    success: function (url) {
                        previewLink(url);
                        $('#aPreview').trigger("click");
                    }
                });
            },
            openNewWindow = function (url) {
                window.open(url, "newwin");
            },
            cancelSaveItem = function () {
                $('.prj-save-div').hide(500);
            },
            openSaveItemBox = function () {
                $('.prj-save-div').show(500);
            },
            closeTemplatesBox = function () {
                $('.templates-select').hide(500);
            },
            openTemplatesBox = function () {
                $('.templates-select').show(500);
            },
            closeProjectsBox = function () {
                $('.projects-select').hide(500);
            },
            openProjectsBox = function () {
                $('.projects-select').show(500);
            },
            initEditorSize = function ()
            {
                var width = $(window).width();
                var height = $(window).height() - 100;

                ratio = height / maxHeight;
                $('#ed-scr').width(maxWidth * ratio);
                $('#ed-scr').height(maxHeight * ratio);
                maxWidth = maxWidth * ratio;
                maxHeight = maxHeight * ratio;
            };

            return {
                //gotoPage: gotoPage,
                uiInit: uiInit,
                initData: initData,
                CommonGalleries: CommonGalleries,
                Item : Item,
                Items : Items,
                Templates : Templates,
                Galleries: Galleries,
                backgroundControlTabChanged: backgroundControlTabChanged,
                backgroundSelect: backgroundSelect,
                backgroundCancel: backgroundCancel,
                backgroundShow: backgroundShow,
                backgroundOK: backgroundOK,
                setAlign: setAlign,
                setBold: setBold,
                setItalic: setItalic,
                fontSize: fontSize,
                font: font,
                foreground: foreground,
                left: left,
                top: top,
                width: width,
                height: height,
                templateName: templateName,
                templateDescription: templateDescription,
                newTextControl: newTextControl,
                itemControls: itemControls,
                changeFont: changeFont,
                textControlEdit: textControlEdit,
                saveItem: saveItem,
                saveTemplate: saveTemplate,
                cancelTemplate: cancelTemplate,
                openTemplateBox: openTemplateBox,
                exportImage: exportImage,
                cancelSaveItem: cancelSaveItem,
                openSaveItemBox: openSaveItemBox,
                projectName: projectName,
                openTemplatesBox: openTemplatesBox,
                closeTemplatesBox: closeTemplatesBox,
                closeProjectsBox: closeProjectsBox,
                openProjectsBox: openProjectsBox,
                textControlDelete: textControlDelete,
                ratio: ratio,
                initEditorSize: initEditorSize,
                backgroundDownloadUrl: backgroundDownloadUrl,
                downloadBackground: downloadBackground,
                backgroundDownloadMessage: backgroundDownloadMessage,
                uploadBackground: uploadBackground
            };
        }();
        
        my.vm.initEditorSize();
        my.vm.initData();
        ko.applyBindings(my.vm);
        my.vm.uiInit();
        
    }
);